<template>
	<el-drawer :title="titleMap[mode]" v-model="visible" :size="1400" destroy-on-close @closed="$emit('closed')">
		<el-container v-loading="loading">
			<el-main style="padding:0 20px 20px 20px">
				<el-form ref="ruleForm" :model="form" :rules="rules" label-width="100px">
					<el-form-item label="服务对象" prop="msg_type">
						<el-radio-group style="width: 400px;" v-model="form.msg_type">
							<el-radio-button label="客户">客户</el-radio-button>
							<el-radio-button label="员工">员工</el-radio-button>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="订阅分类" prop="category_id">
						<blCategory style="width: 400px;" v-model="form.category_id" model="MsgTemplate" />
					</el-form-item>
					<el-form-item label="订阅名称" prop="msg_name">
						<el-input v-model="form.msg_name" style="width: 400px;"></el-input>
					</el-form-item>
					<el-form-item label="订阅描述" prop="msg_remark">
						<el-input type="textarea" style="width: 400px;" v-model="form.msg_remark" placeholder="请输入内容"
							show-word-limit maxlength="150" :autosize="{minRows: 2}"></el-input>
					</el-form-item>
					<el-form-item label="订阅参数" prop="msg_settings">
						<template v-if="isEditSettings">
							<scCodeEditor v-model="form.msg_settings.sql" style="width: 100%;">
							</scCodeEditor>
							<p><el-button type="primary" style="margin-top: 10px;"
									@click="isEditSettings=false">参数预览</el-button></p>
						</template>
						<template v-else>
							<div style="display: flex;flex-direction: column;">
								<el-descriptions column="1" border>
									<el-descriptions-item align="right" label-align="left"
										v-for="(value,key) in form.msg_variables">
										<template #label>
											<div>
												{{key}}
											</div>
										</template>
										<div
											style="width: 300px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
											{{value}}
										</div>
									</el-descriptions-item>
								</el-descriptions>

								<el-button type="primary" style="margin-top: 10px;"
									@click="isEditSettings=true">编辑</el-button>
							</div>
						</template>
					</el-form-item>

					<el-form-item label="开放订阅" prop="msg_is_available_to">
						<el-radio-group v-model="form.msg_is_available_to">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item label="是否启用" prop="is_enabled">
						<el-radio-group v-model="form.is_enabled">
							<el-radio :label="true">是</el-radio>
							<el-radio :label="false">否</el-radio>
						</el-radio-group>
					</el-form-item>

					<el-form-item label="模板配置" prop="msg_sub_template_mapping">
						<div style="width: 900px;">
							<sc-form-table ref="table" v-model="form.msg_sub_template_mapping"
								:addTemplate="addTemplate" drag-sort placeholder="暂无数据">

								<el-table-column prop="template_code" width="400">
									<template #header>
										<span style="color: red;">*</span><span>模板选择</span>
									</template>
									<template #default="{ row }">
										<el-cascader @change="handleCascaderChange($event,row)" v-model="row.code"
											ref="operatorRef" filterable style="margin-right: 10px;width:380px;"
											:show-all-levels="true" :options="cascaderOptions"
											:props="{multiple: false,emitPath: false}"></el-cascader>
									</template>
								</el-table-column>

								<el-table-column class-name="wrap-content" label="预览" prop="template_preview">
									<template #default="{ row }">
										<div v-html="row.template_preview">

										</div>
									</template>
								</el-table-column>

								<el-table-column class-name="wrap-content" width="150" label="状态"
									prop="template_status">
									<template #default="{ row }">
										{{row.template_status}}
									</template>
								</el-table-column>



							</sc-form-table>
							<el-alert :title="`注意:消息模板里的参数必须在订阅模板里有才行`" type="success"
								style="margin-bottom:0px;"></el-alert>
						</div>

					</el-form-item>


					<div style="height: 800px;">
						&nbsp;
					</div>
				</el-form>
			</el-main>
			<el-footer>
				<el-button type="primary" :loading="isSaveing" @click="submit">保存</el-button>
				<el-button @click="visible=false">取消</el-button>
			</el-footer>
		</el-container>
	</el-drawer>
</template>

<script>
	var _this;

	import {
		defineAsyncComponent
	} from 'vue';
	const scEditor = defineAsyncComponent(() => import('@/components/scEditor'));

	export default {
		emits: ['success', 'closed'],
		components: {
			scEditor
		},
		data() {
			return {
				cascaderOptions: [],
				isEditSettings: false,
				props: {
					label: 'title',
					value: 'id',
					keyword: 'keyword'
				},
				activeTab: 'basic',
				data: {

				},
				loading: false,
				mode: "add",
				titleMap: {
					add: '添加订阅模板',
					edit: '编辑订阅模板'
				},
				form: {
					id: '',
					msg_type: "客户",
					msg_sub_template_mapping: [],
					msg_is_available_to: true,
					is_enabled: false,
					msg_settings: {
						sql: '',
						params: {}
					},
					msg_name: '',
					msg_remark: '',
					msg_variables: [],
					category_id: null
				},
				rules: {
					category_id: [{
						required: true,
						message: '订阅分类必选'
					}],
					msg_name: [{
						required: true,
						message: '订阅名称必填'
					}],
				},
				addTemplate: {

				},
				visible: false,
				isSaveing: false,
				apiObj: null,
			}
		},
		mounted() {
			_this = this;
			this.$API.system.msgTemplate.tree.post().then(res => {
				this.cascaderOptions = res.data;
			})
		},
		methods: {

			forNode(node, callback) {
				// 检查 node 是否为数组
				if (Array.isArray(node)) {
					// 如果传入的是数组，递归遍历每个元素
					node.forEach(child => this.forNode(child, callback));
				} else {
					// 处理单个节点
					callback(node);
					// 如果有 children 则继续递归
					if (node.children) {
						node.children.forEach(child => this.forNode(child, callback));
					}
				}
			},
			handleCascaderChange(value, row) {
				this.forNode(this.cascaderOptions, (item) => {
					if (item.value == value) {

						row.template_status = '';

						const {
							variables
						} = item.data;

						let result = true;

						variables.forEach(key => {
							if (!this.form.msg_variables.hasOwnProperty(key)) {
								row.template_status = `缺少[${key}]\r\n${row.template_status||''}`;
								this.$message.error(`缺少[${key}]`);
								result = false;
							}
						})

						if (result === true) {
							row.template_status = '通过';
						}

						Object.keys(item.data).forEach(key => {
							row[key] = item.data[key];
						})

						row.template_preview = row.content;

						variables.forEach(key => {
							if (this.form.msg_variables.hasOwnProperty(key)) {
								row.template_preview = row.template_preview.replaceAll("${" + key + "}",
									this.form.msg_variables[key]);
							}
						})
					}
				})
			},
			test() {

			},
			handleEdit(row, column) {
				if (!row.editing) {
					row.editing = true;
					row.editingColumn = column;
					this.$nextTick(() => {
						const refName = `select-${column}-${row.id}`
						this.$refs[refName]?.toggleMenu()
					})
				}
			},

			success(res) {
				return true;
			},
			//显示
			open(data) {

				this.apiObj = this.$parent.apiObj

				if (data) {
					this.mode = data;
				}
				this.visible = true;
				this.$nextTick(() => {
					if (this.mode == 'add') {
						//this.addTemplate.task_metric_type = 'test';
						this.$refs.table.rowAdd()
					}
				})
				return this;
			},
			//表单提交方法
			submit() {

				this.form.act_action = {
					action: 'navigateTo',
					options: {
						url: "/pages/me/point/point"
					}
				}

				this.$refs.ruleForm.validate(async (data) => {
					if (data) {
						/*
												if (this.form.tasks.length > 0) {
													this.form.tasks.forEach((item, index) => {
														item.order = index;
													})
												}
						*/
						var res;
						this.isSaveing = true;
						if (this.mode == 'add') {
							res = await _this.apiObj.create.post(this.form);
						} else {
							res = await _this.apiObj.update.post(this.form);
						}
						this.isSaveing = false;
						if (res.code == 0) {
							this.$emit('success', data, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						} else {
							this.$alert(res.message, "提示", {
								type: 'error'
							})
						}
					}
				})
			},
			//表单注入数据
			setData(data) {
				this.loading = true

				if (!data.id) {
					if (data.category_id) {
						this.form.category_id = data.category_id
					}
					this.loading = false
					return;
				}

				const params = {
					id: data.id
				}
				setTimeout(async () => {
					var res = await _this.apiObj.show.get(params)
					this.form = res.data
					if (!this.form.msg_settings) {
						this.form.msg_settings = {
							sql: ''
						};
					}
					this.isEditSettings = !this.form.msg_variables;
					this.loading = false
				}, 0)
			}
		}
	}
</script>

<style scoped>
	.custom-empty {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #8c939d;
		border-radius: 5px;
	}

	.custom-empty i {
		font-size: 30px;
		color: #fff;
	}

	.custom-empty p {
		font-size: 12px;
		font-weight: normal;
		color: #fff;
		margin-top: 10px;
	}



	.wrap-content .call {
		white-space: pre-line;
		/* 或 pre-wrap */
		word-break: break-all;
	}
</style>
